const { Admin } = require('../models/adminModel');
const jwt = require('jsonwebtoken');
//登录
async function login(req, res) {
    try {
        const { account, password,status } = req.body;
        const data = await Admin.find({ account, password,status });
        // console.log(data);
        if (data.length > 0) {
            const role = data[0].status;
            const _id = data[0]._id;
            const token = jwt.sign(
                { account },//保存用户信息
                'xiaoyunpeng',//编码字符串
                { expiresIn: 60 * 60 } //token有效期
            );
            res.send({
                msg: '登录成功',
                status: 1,
                data: {
                    userInfo: { account, role, _id },
                    token,
                },
            });
        } else {
            res.send({
                msg: '登录失败',
                status: 0
            });
        }

    } catch (error) {
        console.log('error', error);
    }
}
//注册
async function addAdmin(req, res) {
    try {
        const { account, password, status } = req.body;
        const data = await Admin.find({ account });
        // console.log(data);
        if (data.length > 0) {
            res.send({
                msg: '注册失败，用户已经存在',
                status: 0
            });
        } else {
            const data = await Admin.create({ account, password, status });
            // console.log(data);
            if (data) {
                res.send({
                    msg: '注册成功',
                    status: 1
                });
            } else {
                res.send({
                    msg: '注册失败',
                    status: 0
                });
            }

        }
    } catch (error) {
        console.log('error', error);
    }


}
//删除管理员
async function delAdmin(req, res) {
    try {
        const { _id } = req.body;
        const data = await Admin.deleteOne({ _id });
        console.log(data);
        if (data.deletedCount) {
            res.send({
                msg: "删除成功",
                status: 1
            });
        } else {
            res.send({
                msg: '删除失败',
                status: 0
            })
        }
    } catch (error) {
        console.log('error', error);
    }
}
//通过id查询管理员
async function findAdminByID(req, res) {
    try {
        const { _id } = req.body;
        const data = await Admin.findById({ _id });
        console.log(data);
        if (data) {
            res.send({
                msg: '获取成功',
                status: 1,
                data,
            });
        } else {
            res.send({
                msg: '获取失败',
                status: 0,
            });
        }
    } catch (error) {
        res.send({
            msg: '获取失败',
            status: 0,
        });
        console.log('error', error);
    }
}

//修改管理员信息
async function changeAdminInfo(req, res) {
    try {
        const { _id, account, password, status } = req.body;
        const data = await Admin.updateOne({ _id }, { account, password, status });
        console.log(data);
        if (data.nModified) {
            res.send({
                msg: '数据修改成功',
                status: 1
            });
        } else {
            res.send({
                msg: '数据修改失败',
                status: 0
            });
        }
    } catch (error) {
        console.log('error', error);
        res.send({
            msg: '数据修改失败',
            status: 0
        });
    }
}
//查询所有管理员
async function findAllAdmins(req, res) {
    try {
        const { pageSize = 10, pageNumber = 1 } = req.body;
        //总条数
        const total = await Admin.countDocuments();
        //总页数
        const totalPages = Math.ceil(total / pageSize);
        const data = await Admin
            .find()
            .limit(pageSize - 0) //设置请求的条数
            .skip((pageNumber - 1) * pageSize)  //设置跳过的条数
        console.log(data);
        res.send({
            msg: '数据获取成功',
            status: 1,
            data: { total, totalPages, data, pageSize, pageNumber }
        });

    } catch (error) {
        console.log('error', error);
        res.send({
            msg: '数据获取失败',
            status: 0
        });
    }
}
//判断用户是否登录
async  function isLogin(req,res){
    // console.log('用户登录了才能进来');
    //如果执行该方法。说明用户的token是有效地
    const auth = req.get('Authorization');
    console.log(auth);
    const token = auth.split(' ')[1];
    // console.log(token);
    const data = jwt.verify(token,'xiaoyunpeng');
    // console.log(data);
    res.send({
      status:1,
      msg:'用户已经登录',
      data:data.username
    })
  }
module.exports = { login, addAdmin, delAdmin, changeAdminInfo, findAdminByID, findAllAdmins, isLogin };